package cn.gzjp.modules.woms.web.front;


import cn.gzjp.common.config.Global;
import cn.gzjp.common.constant.Constants;
import cn.gzjp.common.utils.FileUtils;
import cn.gzjp.common.web.AjaxResult;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.woms.entity.Event;
import cn.gzjp.modules.woms.entity.Worker;
import cn.gzjp.modules.woms.service.EventService;
import cn.gzjp.modules.woms.service.WorkerService;
import cn.gzjp.modules.wx.service.QyWxService;
import cn.hutool.core.util.ImageUtil;
import cn.hutool.core.util.StrUtil;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.cp.api.WxCpService;
import org.apache.commons.io.FilenameUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;


/**
 * 企业号--故障确认应用 (内场运维人员，就是批量导入工单拿货，炜鑫鸟人新增的需求)
 *
 */ 
@Controller
@RequestMapping(value = "${frontPath}/achieve")
@SessionAttributes(value = { "corpId", "agentId", "userId" })
public class AchieveController extends BaseController {
	
	@Autowired
	private WorkerService workerService;
	@Autowired
	private EventService eventService;
	@Autowired
	private QyWxService qyWxService;


	
	/**
	 * 未处理列表展示(未处理菜单)
	 * @param userId
	 * @param model
	 * @return
	 */
	@RequestMapping("undo")
	public String undo(@ModelAttribute("userId") String userId,Model model) {
	     Worker worker = workerService.get(userId);
	     Event event = new Event();
		 event.setStatus(Constants.EventStatus.complete);
	     event.setInProjects(worker.getProjectsList());
		 //event.setAchieve(Constants.EventAchieveStatus.NO);
		 event.setCreaterId(userId);
	     List<Event> eventList = eventService.findList(event);

			Collections.sort(eventList, new Comparator<Event>(){
				public int compare(Event o1, Event o2) {
					if(o1.getLeftMinutes() > o2.getLeftMinutes()){
						return 1;
					}
					if(o1.getLeftMinutes() == o2.getLeftMinutes()){
						return 0;
					}
					return -1;
				}
			});

	     model.addAttribute("eventList",eventList);
		 return "modules/woms/front/achieve/undoList";
	}



	/**
	 * 已处理工单列表(已处理菜单)
	 * @param userId
	 * @param model
	 * @return
	 */
	@RequestMapping("done")
	public String done(@ModelAttribute("userId") String userId,Model model) {
		Worker worker = workerService.get(userId);
		Event event = new Event();
		event.setStatus(Constants.EventStatus.achieved);
		event.setInProjects(worker.getProjectsList());
		//event.setAchieve(Constants.EventAchieveStatus.YES);
		event.setCreaterId(userId);
		List<Event> eventList = eventService.findList(event);
		Collections.sort(eventList, new Comparator<Event>(){
			public int compare(Event o1, Event o2) {
				if(o1.getLeftMinutes() > o2.getLeftMinutes()){
					return 1;
				}
				if(o1.getLeftMinutes() == o2.getLeftMinutes()){
					return 0;
				}
				return -1;
			}
		});
		model.addAttribute("eventList",eventList);
		return "modules/woms/front/achieve/doneList";
	}

	/**
	 * 详细展示
	 * @param id  工单id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "event", method = RequestMethod.GET)
	public String event(String id,Model model){
		Event event = eventService.get(id);
		model.addAttribute("event", event);
		return "modules/woms/front/achieve/event";
	}

	/**
	 * 故障确认
	 * @param id  工单id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "achieveUI", method = RequestMethod.GET)
	public String achieveUI(String id,Model model){
		Event event = eventService.get(id);
		model.addAttribute("event", event);
		return "modules/woms/front/achieve/achieve";
	}

	/**
	 * 故障确认
	 * @param id
	 * @param status  4未修复,6已修复
	 * @param content 回复内容
	 * @return
	 */
	@RequestMapping(value = "achieve", method = RequestMethod.POST)
	@ResponseBody
	public String achieve(@ModelAttribute("userId") String userId,String id,String status,String content,String[] pics) {
		Event event = eventService.get(id);
		Worker worker = workerService.get(userId);
		event.setStatus(status);
		eventService.achieve(event,userId,content,pics);
		if(status.equals(Constants.EventStatus.unachieve)){
			sendQyWxMessage(event, Constants.AgentId.enginer,"工单还需继续处理","您处理的工单已被内场运营人员"+worker.getName()+"回复为未修复,请尽快处理",event.getReceiverId());
		}else{
			sendQyWxMessage(event, Constants.AgentId.enginer,"工单已确认修复完成","您处理的工单已被内场运营人员"+worker.getName()+"回复为已修复",event.getReceiverId());
		}
		//推送给自己
		sendQyWxMessage(event, Constants.AgentId.achieve,"修复确认回复成功","你成功回复了故障信息",userId);
		AjaxResult ajaxResult = new AjaxResult();
		ajaxResult.setSuccess(true);
		ajaxResult.setMsg("工单处理成功");
		return this.mapper.toJson(ajaxResult);
	}


	/**
	 * 用于页面js授权
	 * @param corpId
	 * @param url
	 * @return
	 */
	@RequestMapping(value = "jsApi", method = RequestMethod.POST)
	@ResponseBody
	public String jsApi(@ModelAttribute(value = "corpId") String corpId,
						@RequestParam("url") String url) {
		AjaxResult ajaxResult = new AjaxResult();
		WxJsapiSignature jspTitck;
		try {
			WxCpService wxCpService = this.qyWxService.getWxCpService(corpId,
					Constants.AgentId.achieve);
			jspTitck = wxCpService.createJsapiSignature(url);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("timestamp", jspTitck.getTimestamp());
			map.put("nonceStr", jspTitck.getNoncestr());
			map.put("signature", jspTitck.getSignature());
			ajaxResult.setSuccess(true);
			String json = mapper.toJson(map);
			ajaxResult.setMsg(json);
		} catch (Exception e) {
			ajaxResult.setSuccess(false);
		}
		return mapper.toJson(ajaxResult);
	}

	/**
	 * 图片上传
	 * @param corpId
	 * @param userId
	 * @param mediaId
	 * @return
	 */
	@RequestMapping(value = "uploadPic")
	@ResponseBody
	public String uploadPic(@ModelAttribute("corpId") String corpId,
							@ModelAttribute("userId") String userId, String mediaId,
							HttpServletRequest request) {
		AjaxResult result = new AjaxResult(true, "操作成功！");
		try {
			WxCpService wxCpService = this.qyWxService.getWxCpService(corpId,
					Constants.AgentId.achieve);
			File srcFile = wxCpService.mediaDownload(mediaId);
			String extension = FilenameUtils.getExtension(srcFile.getName());
			// 文件保存路径
			String realPath = Global.USERFILES_BASE_URL + "/file/";
			// 转存文件
			FileUtils.createDirectory(Global.getUserfilesBaseDir() + realPath);
			String destFileName = mediaId + "." + extension;
			File destFile = new File(Global.getUserfilesBaseDir() + realPath + destFileName);
			FileUtil.copyFile(srcFile, destFile);
			String destFileNameScale = mediaId + "_s." + extension;
			File destFileScale = new File(Global.getUserfilesBaseDir() + realPath + destFileNameScale);
			ImageUtil.scale(destFile,destFileScale,0.3f);//压缩
			String img = request.getContextPath() + realPath + destFileNameScale;
			result.setSuccess(true);
			result.setMsg(img);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(true);
			result.setMsg("失败");
		}
		return this.mapper.toJson(result);
	}

}
